/**
 * @author yxw
 * date : 2013年9月30日 下午3:50:36 
 */
package com.tzinfo.tzb;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.galhttprequest.GalHttpRequest;
import com.galhttprequest.GalHttpRequest.GalHttpLoadTextCallBack;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tzinfo.data.TztData;
import com.tzinfo.tzb.domain.DiaryList;
import com.tzinfo.tzb.domain.GetCount;
import com.tzinfo.tzb.domain.Tzb_UserInfoModel;
import com.tzinfo.tzb.util.TzbCommonData;
import com.tzinfo.tzt.R;
import com.yxw.util.OutLog;
import com.yxw.util.YXWDateUtil;
import com.yxw.util.YXWImageFactory;
import com.yxw.view.NoScrollListView;
import com.yxw.view.YXWVerticalScrollView;
import com.yxw.view.adapter.ImageAdapter;
import com.yxw.view.util.ResFinder;

public class TzbTabMyActivity extends TzbBaseActivity {

    // 标志
    public static boolean isNeedReflash = false;
    public static boolean reflashInfo = false;
    public static boolean isNeedReLoadNum = false;
    public boolean isReload = false;
    private boolean isMine = true;
    // 数据
    private Tzb_UserInfoModel userInfoModel = null;
    private DiaryList diaryList = null;
    // UI组件
    private ImageView img_touxiang;
    private TextView[] dongtaiTextView = new TextView[3];
    private TextView text_gexingqianming;
    private TextView text_no_riji;
    private TextView text_num_tezi;
    private NoScrollListView listView;
    private YXWVerticalScrollView verticalscrollview;


    // 适配器
    private ImageAdapter imageAdapter;

    public static TzbTabMyActivity activity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        activity = this;
        setContentView(R.layout.tzb_ac_main_my);
        text_num_tezi=(TextView)findViewById(R.id.text_num_tezi);

        isMine = this.getIntent().getBooleanExtra("isMine", true);
        if (isMine && TzbCommonData.diaryList != null) {
            diaryList = TzbCommonData.diaryList;
        }
        init();
        initData();
    }

    private void init() {
        dongtaiTextView[0] = (TextView) ResFinder.findViewById(this,
                "R.id.text_num_guanzhu");
        dongtaiTextView[1] = (TextView) ResFinder.findViewById(this,
                "R.id.text_num_fensi");
        dongtaiTextView[2] = (TextView) ResFinder.findViewById(this,
                "R.id.text_num_shoucang");
        text_gexingqianming = (TextView) ResFinder.findViewById(this,
                "R.id.text_gexingqianming");
        text_no_riji = (TextView) ResFinder.findViewById(this,
                "R.id.text_no_riji");
        img_touxiang = (ImageView) ResFinder.findViewById(this,
                "R.id.img_touxiang");
        listView = (NoScrollListView) ResFinder.findViewById(this,
                "R.id.listView");
        verticalscrollview = (YXWVerticalScrollView) ResFinder.findViewById(
                this, "R.id.verticalscrollview");
        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                if (diaryList != null) {
                    Intent intent = new Intent(TzbTabMyActivity.this,
                            TzbMyDirayDetailActivity.class);
                    TzbCommonData.diaryItem = arg2;
                    TzbTabMyActivity.this.startActivityForResult(intent, 1);
                }
            }
        });

        // 设置圆角
        img_touxiang
                .setImageBitmap(YXWImageFactory.toRoundCorner(BitmapFactory
                        .decodeResource(getResources(), ResFinder.getR(this,
                                "R.drawable.tzb_no_touxiang")), 20));
    }

    public void initData() {
        if (TztData.userInfo == null) {
            Toast.makeText(this, "亲，请先登录才能使用该功能", Toast.LENGTH_SHORT).show();
            verticalscrollview.setVisibility(View.GONE);
            isReload = true;
            return;
        }
        verticalscrollview.setVisibility(View.VISIBLE);
        dialog.show();
        getInfoNum();
        getUserInfo();
        if (diaryList == null) {
            getRizhi();
        } else {
            setRijiUI();
        }
    }

    private void getInfoNum() {
        GalHttpRequest galHttpRequest4 = new GalHttpRequest(this);
        galHttpRequest4.setCacheEnable(false);
        String url4 = ResFinder.getResString(this, "R.string.tzb_url_GetCount")
                + "?sessionid=" + TztData.userInfo.getData().getSessionID()
                + "&type=4";
        galHttpRequest4.setURL(url4);
        galHttpRequest4.startAsynRequestString(new GalHttpLoadTextCallBack() {

            @Override
            public void textLoaded(String arg0) {
                Gson gson = new Gson();
                java.lang.reflect.Type type = new TypeToken<GetCount>() {
                }.getType();
                GetCount count = gson.fromJson(arg0, type);
                if (count.isSuccess()) {
                    text_num_tezi.setText(count.getData().getCount() + "");
                }

            }
        });

        GalHttpRequest galHttpRequest3 = new GalHttpRequest(this);
        galHttpRequest3.setCacheEnable(false);
        //粉丝数
        String url3 = ResFinder.getResString(this, "R.string.tzb_url_GetCount")
                + "?sessionid=" + TztData.userInfo.getData().getSessionID()
                + "&type=3";
        galHttpRequest3.setURL(url3);
        galHttpRequest3.startAsynRequestString(new GalHttpLoadTextCallBack() {

            @Override
            public void textLoaded(String arg0) {
                Gson gson = new Gson();
                java.lang.reflect.Type type = new TypeToken<GetCount>() {
                }.getType();
                GetCount count = gson.fromJson(arg0, type);
                if (count.isSuccess()) {
                    dongtaiTextView[1].setText(count.getData().getCount() + "");
                }

            }
        });
        GalHttpRequest galHttpRequest2 = new GalHttpRequest(this);
        galHttpRequest2.setCacheEnable(false);
        //关注数
        String url2 = ResFinder.getResString(this, "R.string.tzb_url_GetCount")
                + "?sessionid=" + TztData.userInfo.getData().getSessionID()
                + "&type=2";
        galHttpRequest2.setURL(url2);
        galHttpRequest2.startAsynRequestString(new GalHttpLoadTextCallBack() {

            @Override
            public void textLoaded(String arg0) {
                Gson gson = new Gson();
                java.lang.reflect.Type type = new TypeToken<GetCount>() {
                }.getType();
                GetCount count = gson.fromJson(arg0, type);
                if (count.isSuccess()) {
                    dongtaiTextView[0].setText(count.getData().getCount() + "");
                }

            }
        });

        GalHttpRequest galHttpRequest1 = new GalHttpRequest(this);
        galHttpRequest1.setCacheEnable(false);
        String url1 = ResFinder.getResString(this, "R.string.tzb_url_GetCount")
                + "?sessionid=" + TztData.userInfo.getData().getSessionID()
                + "&type=1";
        galHttpRequest1.setURL(url1);
        galHttpRequest1.startAsynRequestString(new GalHttpLoadTextCallBack() {

            @Override
            public void textLoaded(String arg0) {
                Gson gson = new Gson();
                java.lang.reflect.Type type = new TypeToken<GetCount>() {
                }.getType();
                GetCount count = gson.fromJson(arg0, type);
                if (count.isSuccess()) {
                    dongtaiTextView[2].setText(count.getData().getCount() + "");
                }
            }
        });
    }

    private void getUserInfo() {
        if(TzbCommonData.userInfoModel!=null&&TzbCommonData.userInfoModel.isSuccess()){
            userInfoModel=TzbCommonData.userInfoModel;
            text_gexingqianming.setText("个性签名："
                    + userInfoModel.getData().getSignature());
            imageLoader.displayImage(userInfoModel.getData()
                    .getAvatar(), img_touxiang, options);
            return;
        }
        GalHttpRequest userInfoHttpRequest = new GalHttpRequest(this);
        userInfoHttpRequest.setCacheEnable(false);
        String url4 = ResFinder.getResString(this,
                "R.string.tzb_url_Tzb_UserInfoModel")
                + "?username="
                + TztData.userInfo.getData().getUserName();
        OutLog.LogE("yxw", "user:" + url4);
        userInfoHttpRequest.setURL(url4);
        userInfoHttpRequest
                .startAsynRequestString(new GalHttpLoadTextCallBack() {

                    @Override
                    public void textLoaded(String arg0) {
                        Gson gson = new Gson();
                        java.lang.reflect.Type type = new TypeToken<Tzb_UserInfoModel>() {
                        }.getType();
                        userInfoModel = gson.fromJson(arg0, type);
                        removeProgressBar();
                        if (userInfoModel.isSuccess()) {
                            OutLog.LogE("yxw", "touxiang:"
                                    + userInfoModel.getData().getAvatar());
                            TzbCommonData.userInfoModel = userInfoModel;
                            text_gexingqianming.setText("个性签名："
                                    + userInfoModel.getData().getSignature());
                            imageLoader.displayImage(userInfoModel.getData()
                                    .getAvatar(), img_touxiang, options);
                        }
                    }
                });
    }

    private void getRizhi() {
        GalHttpRequest rizhiHttpRequest = new GalHttpRequest(this);
        rizhiHttpRequest.setCacheEnable(false);
        String url = ResFinder.getResString(this, "R.string.tzb_url_DiaryList")
                + "?username=" + TztData.userInfo.getData().getUserName()
                + "&Page=1" + "&Pagesize=5";
        OutLog.LogE("yxw", "Rizhi:" + url);
        rizhiHttpRequest.setURL(url);
        rizhiHttpRequest.startAsynRequestString(new GalHttpLoadTextCallBack() {

            @Override
            public void textLoaded(String arg0) {
                Gson gson = new Gson();
                java.lang.reflect.Type type = new TypeToken<DiaryList>() {
                }.getType();
                diaryList = gson.fromJson(arg0, type);
                if (diaryList != null && diaryList.isSuccess()
                        && diaryList.getData().size() > 0) {
                    isReload = false;
                    TzbCommonData.diaryList = diaryList;
                    setRijiUI();
                } else {
                    listView.setVisibility(View.GONE);
                    text_no_riji.setVisibility(View.VISIBLE);
                }
                dialog.dismiss();
            }
        });
    }

    private void setRijiUI() {
        diaryList = TzbCommonData.diaryList;
        if (diaryList == null) {
            getRizhi();
            return;
        }
        listView.setVisibility(View.VISIBLE);
        text_no_riji.setVisibility(View.GONE);
        List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < diaryList.getData().size(); i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            if (diaryList.getData().get(i).getPhoto().size() > 0) {
                String imageUil = diaryList.getData().get(i).getPhoto().get(0)
                        .getPicfile();
                map.put("image", imageUil);
            } else {
                map.put("image", ResFinder.getR(this, "R.drawable.ic_empty"));
            }

            map.put("title", diaryList.getData().get(i).getTitle());
            String time = YXWDateUtil.getTimeByDayInterval(diaryList.getData()
                    .get(i).getPtime(), "yyyy-MM-dd HH:mm");
            map.put("time", time);
            map.put("username", diaryList.getData().get(i).getUsername());
            map.put("supports", diaryList.getData().get(i).getSupports());
            data.add(map);
        }
        imageAdapter = new ImageAdapter(this, data, ResFinder.getR(this,
                "R.layout.tzb_item_riji"), new String[] { "image", "title",
                "time", "username", "supports" }, new int[] {
                ResFinder.getR(this, "R.id.list_item_image"),
                ResFinder.getR(this, "R.id.list_item_title"),
                ResFinder.getR(this, "R.id.list_item_time"),
                ResFinder.getR(this, "R.id.list_item_netname"),
                ResFinder.getR(this, "R.id.list_item_supports") });
        listView.setAdapter(imageAdapter);
        removeProgressBar();
        dialog.dismiss();
    }

    // onclick
    public void goWriteDiray(View v) {
        Intent intent = new Intent(this, TzbMyDirayWriteActivity.class);
        startActivityForResult(intent, 1);
    }

    // onclick
    public void goModifyInfo(View v) {
        if (TztData.isUserLogin) {
            Intent intent = new Intent(this, TzbMyModifyActivity.class);
            startActivityForResult(intent, 1);
        }
    }

    // onclick
    public void goAllDirayList(View v) {
        Intent intent = new Intent(this, TzbDirayListActivity.class);
        startActivity(intent);
    }

    // onclick
    public void goDongtaiDetial(View v) {
        Intent intent = null;
        if (v.getId() == ResFinder.getR(this, "R.id.layout_dongtai01")) {
            // 关注
            intent=new Intent(this, TzbMyFansActivity.class);
            intent.putExtra("isFans", false);
            startActivity(intent);
        } else if (v.getId() == ResFinder.getR(this, "R.id.layout_dongtai02")) {
            // 粉丝
            intent=new Intent(this, TzbMyFansActivity.class);
            intent.putExtra("isFans", true);
            startActivity(intent);

        } else if (v.getId() == R.id.layout_dongtai03) {
            // 收藏
            intent = new Intent(this, TzbMyShoucangActivity.class).putExtra("title","收藏");
            startActivity(intent);
        }else if (v.getId() == R.id.layout_dongtai04) {
            // 我的
            intent = new Intent(this, TzbMyPostActivity.class);
            startActivity(intent);
        }
    }

    @Override
    protected void onResume() {

        super.onResume();
    }

    public void onReFlash() {
        OutLog.LogE("yxw", "onReFlash");
        if (isNeedReflash) {
            showProgressBar();
            getRizhi();
            isNeedReflash = false;
        }
    }

    public void onReFlashInfo() {
        OutLog.LogE("yxw", "onReFlashInfo");
        if (reflashInfo) {
            showProgressBar();
            getUserInfo();
            reflashInfo = false;
        }
    }

    public void onReFlashNum() {
        OutLog.LogE("yxw", "onReFlashNum");
        if (isNeedReLoadNum) {
            showProgressBar();
            getInfoNum();
            isNeedReLoadNum = false;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        OutLog.LogE("yxw", "onActivityResult");
        if (requestCode == 1 && resultCode == 1) {
            boolean isNeedReflash = data.getBooleanExtra(TzbCommonData.IS_OK,
                    false);
            if (isNeedReflash) {
                setRijiUI();
            }
        }
    }
}
